package com.zwt.controller;

import com.alibaba.fastjson.JSONObject;
import com.zwt.constant.RedisConstant;
import com.zwt.constant.RedisKeyUtil;
import com.zwt.constant.SourceType;
import com.zwt.model.TAccountUser;
import com.zwt.model.UserInfo;
import com.zwt.redis.Redis;
import com.zwt.result.ResultBean;
import com.zwt.result.ResultCode;
import com.zwt.service.TAccountUserService;
import com.zwt.util.TRegular;
import com.zwt.util.TString;
import com.zwt.util.TTime;
import com.zwt.util.token.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


/**
 * Created by zwt on 2018/9/6.
 * APP 注册流程
 */
@RestController
@RequestMapping("/baseServer/reg")
public class RegisterController {

    private static Logger logger = LoggerFactory.getLogger(RegisterController.class);

    @Autowired
    private TAccountUserService tAccountUserService;

    @Autowired
    private Redis redis;


    /**
     * 注册
     * @param phone
     * @param code
     * @param name
     * @param pushId
     * @return
     */
    @RequestMapping("register")
    public ResultBean<JSONObject> register(@RequestParam String phone, @RequestParam String code,
                                           @RequestParam String name,
                                           String pushId){
        ResultBean<JSONObject> result = new ResultBean<>();
        JSONObject data = new JSONObject();
        if (StringUtils.isBlank(phone)) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"手机号为空");
            result.setMessage("手机号不能为空!");
            return result;
        }
        if (!TRegular.validatePhone(phone)) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"手机号格式错误");
            result.setMessage("手机号码格式错误!");
            return result;
        }
        if (StringUtils.isBlank(name)) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"姓名"+name+"为空");
            result.setMessage("姓名不能为空!");
            return result;
        }
        if (name.length() > 20) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"姓名"+name+"超过了20位");
            result.setMessage("姓名不能超过20位!");
            return result;
        }
        if (TString.isConSpeCharacters(name)) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"姓名"+name+"包含了特殊字符");
            result.setMessage("姓名不能包含特殊字符!");
            return result;
        }
        if (StringUtils.isBlank(phone)) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"验证码为空");
            result.setMessage("验证码不能为空!");
            return result;
        }
        //redis中获取验证码
        String redisCode = redis.get(RedisKeyUtil.getRegCache(phone), String.class);
        if (StringUtils.isBlank(redisCode)) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"验证码已失效");
            result.setMessage("验证码已失效!");
            return result;
        }
        if (!code.trim().equals(redisCode)) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"验证码错误");
            result.setMessage("验证码错误, 请检查!");
            return result;
        }
        TAccountUser tAccountUser = tAccountUserService.selectByPhone(phone);
        if(null!=tAccountUser){
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"该手机号已经被注册");
            result.setMessage("该手机号已被注册!");
            return result;
        }
        tAccountUser.setUserName(name);
        tAccountUser.setUserStatus((byte) 1);//使用状态 0：禁用 1：启用
        tAccountUser.setSourceType(SourceType.APP.type); // 来源APP 4
        tAccountUser.setJpushId("1");
        tAccountUser.setAddTime(new Date());
        tAccountUser.setUpdateTime(new Date());
        try {
            int i = tAccountUserService.insert(tAccountUser);
            if(i<=0){
                result.setMessage("操作失败，请稍后再试!");
                return result;
            }
            //将用户信息放入redis 两个月有效期
            String token = TokenUtil.getToken(phone);
            UserInfo userInfo = new UserInfo();
            userInfo.settAccountUser(tAccountUser);
            redis.set(token,UserInfo.class, RedisConstant.MONTH_1*2);
            data.put("token",token);
            data.put("userInfo",userInfo);
            result.setData(data);
            result.setResultCode(ResultCode.SUCCESS.getCode());
        } catch (Exception e) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),e.getMessage());
            result.setMessage("操作失败，请稍后再试!");
            return result;
        }
        return result;
    }


}
